import { loginApi, getInfoApi } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    user: null,
  };
};

const state = getDefaultState();

const mutations = {
  //重置用户信息
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  // SET_TOKEN: (state, token) => {
  //   state.token = token;
  // },
  // SET_NAME: (state, name) => {
  //   state.name = name;
  // },
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar;
  // },
  SET_USER: (state, payload) => {
    state.user = payload;
  },
};

const actions = {
  // 登录方法
  login({ commit }, loginForm) {
    return new Promise((resolve, reject) => {
      loginApi(loginForm)
        .then((response) => {
          if (response.data) {
            //data有数据说明登录成功，将用户信息保存到仓库中
            commit("SET_USER", response.data);
            resolve();
          } else {
            reject(response);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });

    // return new Promise((resolve, reject) => {
    //   loginApi(loginForm)
    //     .then((response) => {
    //       console.log(response);
    //     })
    //     .catch((error) => {
    //       reject(error);
    //     });
    // });
  },

  // 恢复登录状态
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfoApi().then((response) => {
        //返回值为string类型则表示登录过期或未登录
        if (typeof response === "string") {
          response = JSON.parse(response);
          if (response.code === 401) {
            reject(response.msg);
          }
        } else {
          //表示当前token没问题，将返回的用户信息存储到user中
          commit("SET_USER", response.data);
          resolve();
        }
      });
    });
  },

  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken(); // must remove  token  first
      resetRouter();
      commit("RESET_STATE");
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
